package com.daou.smartpush.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.daou.smartpush.common.Config;
import com.daou.smartpush.common.util.Message;
import com.daou.smartpush.domain.license.License;
import com.daou.smartpush.model.company.CompanyModel;
import com.daou.smartpush.model.license.LicenseModel;
import com.daou.smartpush.service.company.CompanyService;
import com.daou.smartpush.service.license.LicenseService;

@Controller
@RequestMapping("/license")
public class LicenseController {

    @Autowired
    LicenseService licenseService;

    @Autowired
    CompanyService companyService;

    @RequestMapping(value = "/createForm", method = RequestMethod.GET)
    public String createFormLicense(HttpServletRequest request,
            @ModelAttribute("licenseModel") LicenseModel LicenseModel) {

        List<CompanyModel> list = companyService.getAllCompanyforCreateLicesense();

        request.setAttribute("company", list);

        return "createLicense";
    }

    @RequestMapping(value = "/updateForm", method = RequestMethod.GET)
    public String updateLicenseForm(HttpServletRequest request,
            @ModelAttribute("licenseModel") LicenseModel LicenseModel) {
        String id = request.getParameter("id").toString();
        LicenseModel tempLicenseModel = licenseService.getLicenseInfo(Long.valueOf(id));

        request.setAttribute("licenseInfo", tempLicenseModel);

        return "updateLicense";
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String createLicense(HttpServletRequest request, @ModelAttribute("licenseModel") LicenseModel licenseModel,
            BindingResult result) {
        License license = licenseService.selectLicenseByHost(licenseModel.getHostId());
        if (license != null) {
            List<CompanyModel> list = companyService.getAllCompanyforCreateLicesense();

            request.setAttribute("company", list);

            result.rejectValue("error_msg", "", Message.getMessage("error.company.existLicense"));
            return "createLicense";
        }
        licenseService.registOrUpdateLicense(licenseModel);

        return "redirect:/";
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String updateLicense(Locale locale, Model model, @ModelAttribute("licenseModel") LicenseModel licenseModel) {

        licenseService.registOrUpdateLicense(licenseModel);

        return "redirect:/";
    }

    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public String downloadLicense(Locale locale, Model model, HttpServletRequest request, HttpServletResponse response) {
        OutputStream out = null;

        LicenseModel licenseModel = licenseService.getLicenseInfo(Long.valueOf(request.getParameter("id").toString()));

        String filePath = Config.filePath + licenseModel.getCompanySeq()
                + "/" + licenseModel.getHostId().replaceAll(":", "") + "/License.lic";

        File downloadFile = new File(filePath);
        
        if(downloadFile.isFile()){
        	response.setContentType("application/octet-stream");
            response.setContentLength((int) downloadFile.length());

            String userAgent = request.getHeader("User-Agent");
            boolean ie = userAgent.indexOf("MSIE") > -1;
            String fileName = null;

            try {
                if (ie) {
                    fileName = URLEncoder.encode(downloadFile.getName(), "utf-8");
                } else {
                    fileName = new String(downloadFile.getName().getBytes("utf-8"), "iso-8859-1");
                }

                response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\";");
                response.setHeader("Content-Transfer-Encoding", "binary");
                out = response.getOutputStream();
                FileInputStream fis = null;

                fis = new FileInputStream(downloadFile);
                FileCopyUtils.copy(fis, out);

                if (fis != null) {
                    fis.close();
                }
                out.flush();
            } catch (Exception e) {
                // TODO: handle exception
            } finally {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } 
        
        return null;
    }

    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String downloadLicense(@RequestParam("id") Long id) {
        boolean result;
        result = licenseService.deleteLicense(id);
        return "redirect:/";
    }
}
